<template>
  <Modal v-model="status"
         title="添加河流事件"
         width="800"
         :mask-closable="false"
         @on-cancel="hide">
    <Form ref="JForm"
          :model="model"
          :rules="rules"
          label-position="left"
          :label-width="80">

      <Form-item label="问题描述"
                 prop="overview">
        <Input v-model="model.overview"
               :maxlength="200"
               placeholder="输入问题描述" />
      </Form-item>

      <Form-item label="事件图片"
                 prop="photos">
        <template v-for="(item,index) in uploadList">
          <div class="demo-upload-list"
               :key="index">
            <img :src="item" />
            <div class="demo-upload-list-cover">
              <Icon type="ios-trash-outline"
                    @click.native="handleRemove(index)"></Icon>
            </div>
          </div>
        </template>

        <Upload ref="JUpload"
                :show-upload-list="false"
                :on-success="handleSuccess"
                :format="['jpg','jpeg','png']"
                :max-size="2048000"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                multiple
                type="drag"
                :action="url"
                style="display: inline-block;width:58px;">
          <div style="width: 58px;height:58px;line-height: 58px;">
            <Icon type="ios-camera"
                  size="20" />
          </div>
        </Upload>
      </Form-item>
      <Form-item label="事件地点"
                 prop="address"
                 style="margin-bottom:30px">
        <!-- <Select v-model="model.address"
                filterable
                remote
                :remote-method="searchArea"
                :loading="mapLoading">
          <Option v-for="(address, index) in addressList"
                  :value="index"
                  :key="index">{{index}}</Option>
        </Select> -->
        <Input v-show="false"
               v-model="model.address" />
        <div class="address-wrapper">
          <Input placeholder="搜索地点" v-model="model.address" @on-change="changeAddress(model.address)" />
          <div class="address-list" v-show="showAddress">
            <ul>
              <li v-for="(item, index) in addressList" :key="index" @click="getAddress(item)">
                {{item.title}}
                <span class="address-text">{{item.address}}</span>
              </li>
            </ul>
          </div>
        </div>
        <div v-if="status"
             id="reportMap"
             style="height: 300px;" />
      </Form-item>
      <FormItem label="问题类型"
                prop="problem_types">
        <CheckboxGroup v-model="model.problem_types">
          <template v-for="problem in problemList">
            <Checkbox :key="problem"
                      :label="problem" />
          </template>
        </CheckboxGroup>
      </FormItem>

      <FormItem label="处理方式"
                required>
        <RadioGroup v-model="model.solve_way"
                    @on-change="chooseHandleWay">
          <Radio label="自行处理" />
          <Radio label="上报处理" />
        </RadioGroup>
      </FormItem>

      <Form-item v-if="model.solve_way==='自行处理'"
                 label="处理结果"
                 prop="solve_result">
        <Input v-model="model.solve_result"
               :maxlength="200"
               show-word-limit
               type="textarea"
               placeholder="请输入处理结果" />
      </Form-item>

      <FormItem label="处理照片"
                prop="solve_file"
                style="margin-bottom:20px"
                v-if="model.solve_way==='自行处理'">
        <template v-for="(item,index) in solveList">
          <div class="demo-upload-list"
               :key="index">
            <img :src="item" />
            <div class="demo-upload-list-cover">
              <Icon type="ios-trash-outline"
                    @click.native="removeSolve(index)"></Icon>
            </div>
          </div>
        </template>

        <Upload ref="JSolve"
                :show-upload-list="false"
                :on-success="uploadSolve"
                :format="['jpg','jpeg','png']"
                :max-size="2048000"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                multiple
                type="drag"
                :action="url"
                style="display: inline-block;width:58px;">
          <div style="width: 58px;height:58px;line-height: 58px;">
            <Icon type="ios-camera"
                  size="20" />
          </div>
        </Upload>
      </FormItem>

    </Form>
    <div slot="footer">
      <Button type="primary"
              @click="addmanual">确定</Button>
      <Button type="text"
              @click="hide">取消</Button>
    </div>
  </Modal>
</template>

<script>
import { domain, domain2 } from 'global/setting';
import { ajaxPost } from 'global/axios';
import storage from 'good-storage';

export default {
  data() {
    return {
      url: `${domain}/filemanage/uploadphoto?dir=patrol/app/manual&token=${storage.session.get(
        'token'
      )}`,
      addressText: '', // 输入框显示的地址（用来显示地址列表中的值）
      addressValue: '', // 实际地址（指‘禅城区天马大厦(佛罗路南)’这种格式的）
      status: false,
      mapLoading: false,
      showAddress: false, // 是否显示地址列表
      isClickMap: false, // 是否点击过地图，用来判断输入框显示的是地址列表中的值，还是地图上的值
      model: {
        _id: '',
        photos: [],
        lng: '',
        address: '',
        solve_result: '',
        lat: '',
        overview: '',
        solve_way: '上报处理',
        solve_file: [],
        problem_types: [],
      },
      rules: {
        overview: [{ required: true, message: '请填写描述', trigger: 'blur' }],
        address: [
          {
            required: true,
            message: '请选择地点',
            trigger: 'blur',
          },
        ],
        problem_types: [
          {
            required: true,
            type: 'array',
            message: '请选择问题类型',
            trigger: 'change',
            min: 1,
          },
        ],
        solve_file: [
          {
            required: true,
            message: '请上传处理照片',
            type: 'array',
            min: 1,
            trigger: 'change',
          },
        ],
        photos: [
          {
            required: true,
            message: '请上传事件照片',
            type: 'array',
            min: 1,
            trigger: 'change',
          },
        ],
        solve_result: [
          {
            required: true,
            message: '请输入处理结果',
            trigger: 'blur',
          },
        ],
      },
      addressList: [],
      uploadList: [],
      solveList: [],
      problemList: [
        '杂物漂浮',
        '污水直排',
        '水体异样',
        '护岸损毁',
        '非法采砂',
        '侵占河道',
        '非法捕鱼',
        '四乱问题',
        '五清问题',
        '其他',
      ],
      mapPath: [] // 地图路径
    };
  },

  mounted() {
    // 点击地址列表以外的区域，将隐藏地址列表
    document.body.addEventListener('click',(e)=>{
        if(e.target.className != 'address-list'){
          this.showAddress = false;
        }
    },false);
  },

  methods: {
    show(row) {
      this.status = true;
      this.$nextTick(() => {
        let { route, _id } = row;
        this.model._id = _id;
        let center = new qq.maps.LatLng(route[0].lat, route[0].lng);

        let map = new qq.maps.Map(document.getElementById('reportMap'), {
          center,
          zoom: 16,
        });

        qq.maps.event.addListener(map, 'click', event => {
          let { latLng } = event;
          let { lat, lng } = latLng;
          let marker = new qq.maps.Marker({
            position: latLng,
            map,
          });

          qq.maps.event.addListener(map, 'click', () => marker.setMap(null));
          this.model.lat = lat;
          this.model.lng = lng;
          this.isClickMap = true; // 刚点击了地图
          this.getStreet(lat, lng);
        });

        let path = route.map(({ lat, lng }) => {
          return new qq.maps.LatLng(lat, lng);
        });

        this.mapPath = [...path]; //保存地图路径

        new qq.maps.Polyline({
          path,
          strokeColor: '#FF0000',
          strokeWeight: 2,
          editable: false,
          map,
        });
      });
    },

    chooseHandleWay() {
      if (this.model.solve_way !== '自行处理') {
        this.model.solve_file = [];
        this.solveList = [];
        this.model.solve_result = '';
        this.$refs.JSolve && this.$refs.JSolve.clearFiles();
      }
    },

    getStreet(lat, lng) {
      let data = {
        location: `${lat},${lng}`,
        key: 'AZ3BZ-RXPLW-DNZRV-RLXEG-NPASJ-EDB5Z',
        get_poi: 0,
      };
      data.output = 'jsonp';
      $.ajax({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/?',
        type: 'get',
        dataType: 'JSONP',
        jsonp: 'callback',
        jsonpCallback: 'QQmap',
        data,
        success: ({
          result: {
            formatted_addresses: { recommend },
          },
        }) => {
          this.addressValue = recommend; // 保存实际地址
          if(this.isClickMap){ // 点击了地图，所以输入框显示的值应该是实际地址
            this.model.address = this.addressValue;
          }
        },
      });
    },

    hide() {
      this.uploadList = [];
      this.solveList = [];
      this.$refs.JUpload.clearFiles();
      this.$refs.JSolve && this.$refs.JSolve.clearFiles();
      this.model = {
        _id: '',
        photos: [],
        lng: '',
        address: '',
        lat: '',
        overview: '',
        solve_way: '上报处理',
        solve_file: [],
        solve_result: '',
        problem_types: [],
      };
      this.$refs.JForm.resetFields();
      this.status = false;
    },

    // searchArea(keyword) {
    //   if (keyword) {
    //     $.ajax({
    //       url: 'https://apis.map.qq.com/ws/place/v1/search?',
    //       type: 'get',
    //       dataType: 'jsonp',
    //       jsonp: 'callback',
    //       jsonpCallback: 'QQmap',
    //       data: {
    //         keyword,
    //         key: 'AZ3BZ-RXPLW-DNZRV-RLXEG-NPASJ-EDB5Z',
    //         boundary: 'region(佛山,0)',
    //       },
    //       success: res => {
    //         console.log(res);
    //       },
    //     });
    //   }
    // },

    // 输入地址
    changeAddress(keyword) {
      if(keyword){
        this.showAddress = true;
        let data = { 
          keyword: keyword,
          region: '佛山',
          key: 'AZ3BZ-RXPLW-DNZRV-RLXEG-NPASJ-EDB5Z'
        };
        data.output = 'jsonp';
        $.ajax({
          url: 'https://apis.map.qq.com/ws/place/v1/suggestion',
          type: 'get',
          dataType: 'JSONP',
          jsonp: 'callback',
          jsonpCallback: 'QQmap',
          data,
          success: (res) => {
            this.addressList = res.data; // 地址列表
          }
        })
      }
    },

    // 选择地址
    getAddress(item) {
      this.showAddress = false; // 选择地址后隐藏地址列表
      this.isClickMap = false;  // 没有点击地图
      this.addressText = item.title;
      let { lat, lng } = item.location;
      let path = this.mapPath;
      let center = new qq.maps.LatLng(lat, lng); // 地图位置
      let map = new qq.maps.Map(document.getElementById('reportMap'), {
        center,
        zoom: 16
      });
      this.model.lat = lat;
      this.model.lng = lng;
      this.setMarker(map, center);
      this.getStreet(lat, lng);
      this.model.address = this.addressText; // 使输入框显示的是选中的地址
      new qq.maps.Polyline({ // 绘制地图路径
        path,
        strokeColor: '#FF0000',
        strokeWeight: 2,
        editable: false,
        map,
      });
    },

    // 设置标注
    setMarker(map, center) {
      let marker = new qq.maps.Marker({
        position: center,
        map,
      });
      this.watchMap(map, marker);
    },

    // 监听地图
    watchMap(map, mar) {
      qq.maps.event.addListener(map, 'click', event => {
        mar.setMap(null);
        let { latLng } = event;
        let { lat, lng } = latLng;
        let marker = new qq.maps.Marker({
          position: latLng,
          map,
        });

        qq.maps.event.addListener(map, 'click', () => marker.setMap(null));
        this.model.lat = lat;
        this.model.lng = lng;
        this.isClickMap = true; // 点击过地图
        this.getStreet(lat, lng);
      });
    },

    handleSuccess({ result }) {
      let { path } = result;
      this.model.photos.push(path);
      this.uploadList.push(`${domain2}${path}`);
    },

    uploadSolve({ result }) {
      let { path } = result;
      this.model.solve_file.push(path);
      this.solveList.push(`${domain2}${path}`);
    },

    handleRemove(index) {
      this.uploadList.splice(index, 1);
      this.model.photos.splice(index, 1);
    },

    removeSolve(index) {
      this.solveList.splice(index, 1);
      this.model.solve_file.splice(index, 1);
    },

    handleMaxSize() {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件大小不能超过20M。',
      });
    },

    handleFormatError() {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: `请上传 jpg 或 png 格式的图片。`,
      });
    },

    addmanual() {
      this.$refs.JForm.validate(valid => {
        if (valid) {
          let data = {};
          for(let key in this.model){
            if(key === 'address'){
              data[key] = this.addressValue;
            }else{
              data[key] = this.model[key];
            }
          }

          if (data.solve_way === '上报处理') {
            delete data.solve_way;
            delete data.solve_file;
            delete data.solve_result;
          }

          ajaxPost({
            data,
            url: '/emergency/report/manualadd',
            token: storage.session.get('token'),
            success: res => {
              if (res.data.code === '0000') {
                this.$Loading.finish();
                this.$Message.success({
                  content: '增加成功',
                });
                this.hide();
                this.$emit('update');
              } else {
                this.$Message.warning({
                  content: res.data.message,
                });
              }
            },
          });
        }
      });
    },
  },
};
</script>

<style lang="less">
/* 搜索地点列表 */
.address-wrapper {
  display: relative;
}
.address-list {
  position: absolute;
  z-index: 1;
  width: 100%;
  max-height: 200px;
  padding: 10px;
  overflow: auto;
  background: #fff;
  border: 1px solid #dcdee2;
  ul {
    li {
      cursor: pointer;
    }
  }
}
.address-text {
  margin-left: 10px;
  font-size: 12px;
  color: #c5c8ce;
  transform: scale(0.8)
}
</style>